/**
 *    Copyright 2009-2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.datasource.unpooled;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public class UnpooledDataSource implements DataSource {
  //这个是数据库的驱动类加载器,目的是从磁盘中加载数据库驱动类到内存
  private ClassLoader driverClassLoader;
  //驱动器属性，这个用于保存我们手动设置的数据库驱动器属性，如果我们不进行设置，则会使用默认值。这个属性设置的键一般都会是以“driver.”为前缀。
  private Properties driverProperties;
  //表示数据库驱动注册器，其内部保存着所有已注册的数据库驱动类实例，这个字段是static修饰的，表示在数据源类加载的时候就会创建，这个时候创建的其实是个空集合。再者使用ConcurrentHashMap集合，这是一个线程安全的键值对型集合，
  private static Map<String, Driver> registeredDrivers = new ConcurrentHashMap<String, Driver>();
  //数据库驱动类名
  private String driver;
  //数据库服务器URL地址
  private String url;
  //数据库服务器连接用户名
  private String username;
  //数据库服务器连接密码
  private String password;
  //是否自动提交，这是一个逻辑值，真表示使用自动提交，假表示关闭自动提交
  private Boolean autoCommit;
  //表示默认的事务级别
  private Integer defaultTransactionIsolationLevel;
  //该静态代码块的作用就是为registeredDrivers集合赋值,保证在该类加载的时候就将默认的驱动器实例加载到静态集合中以备用
  static {
	//DriverManager是JDK提供的驱动器管理类
	//这里调用DriverManager中getDrivers()方法，将会获取DriverManager中在集合registeredDrivers中的保存的驱动器实例，
	//在获取的时候会进行类加载验证，验证的目的是确保使用本类加载器获取的驱动器类与在registeredDrivers中保存的对应驱动类实例的类是
	//同一类型（==）。最后获取到的是驱动实例的枚举。
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
      Driver driver = drivers.nextElement();
      registeredDrivers.put(driver.getClass().getName(), driver);
    }
  }
  /**
   * 无参构造器,这个构造器在数据源工厂的无参构造器中被调用，用于创建一个空的UnpolledDataSource实例，
   * 然后使用工厂类中的setProperties()方法，为这个空实例中的各个字段进行赋值
   * 
   */
  public UnpooledDataSource() {
  }
  /**
   * 构造器
   */
  public UnpooledDataSource(String driver, String url, String username, String password) {
    this.driver = driver;
    this.url = url;
    this.username = username;
    this.password = password;
  }
  /**
   * 构造器
   */
  public UnpooledDataSource(String driver, String url, Properties driverProperties) {
    this.driver = driver;
    this.url = url;
    this.driverProperties = driverProperties;
  }
  /**
   * 构造器
   */
  public UnpooledDataSource(ClassLoader driverClassLoader, String driver, String url, String username, String password) {
    this.driverClassLoader = driverClassLoader;
    this.driver = driver;
    this.url = url;
    this.username = username;
    this.password = password;
  }
  /**
   * 构造器
   */
  public UnpooledDataSource(ClassLoader driverClassLoader, String driver, String url, Properties driverProperties) {
    this.driverClassLoader = driverClassLoader;
    this.driver = driver;
    this.url = url;
    this.driverProperties = driverProperties;
  }
  /**
   * 获取数据源连接,通过调用方法doGetConnection()实现，该方法是真正执行数据库连接并获取这个连接的实现。
   */
  @Override
  public Connection getConnection() throws SQLException {
    return doGetConnection(username, password);
  }
  /**
   * 获取数据源连接,通过调用方法doGetConnection()实现，该方法是真正执行数据库连接并获取这个连接的实现。
   */
  @Override
  public Connection getConnection(String username, String password) throws SQLException {
    return doGetConnection(username, password);
  }
  /**
   * 表示设置数据源连接数据库的最长等待时间，以秒为单位
   */
  @Override
  public void setLoginTimeout(int loginTimeout) throws SQLException {
    DriverManager.setLoginTimeout(loginTimeout);
  }
  /**
   * 表示获取数据源连接到数据库的最长等待时间
   */
  @Override
  public int getLoginTimeout() throws SQLException {
    return DriverManager.getLoginTimeout();
  }
  /**
   * 设置数据源的日志输出者（log writer）为给定的一个PrintWriter实例
   */
  @Override
  public void setLogWriter(PrintWriter logWriter) throws SQLException {
    DriverManager.setLogWriter(logWriter);
  }
  /**
   * 获取数据源的日志输出者。
   */
  @Override
  public PrintWriter getLogWriter() throws SQLException {
    return DriverManager.getLogWriter();
  }

  public ClassLoader getDriverClassLoader() {
    return driverClassLoader;
  }

  public void setDriverClassLoader(ClassLoader driverClassLoader) {
    this.driverClassLoader = driverClassLoader;
  }

  public Properties getDriverProperties() {
    return driverProperties;
  }

  public void setDriverProperties(Properties driverProperties) {
    this.driverProperties = driverProperties;
  }

  public String getDriver() {
    return driver;
  }

  public synchronized void setDriver(String driver) {
    this.driver = driver;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public Boolean isAutoCommit() {
    return autoCommit;
  }

  public void setAutoCommit(Boolean autoCommit) {
    this.autoCommit = autoCommit;
  }

  public Integer getDefaultTransactionIsolationLevel() {
    return defaultTransactionIsolationLevel;
  }

  public void setDefaultTransactionIsolationLevel(Integer defaultTransactionIsolationLevel) {
    this.defaultTransactionIsolationLevel = defaultTransactionIsolationLevel;
  }
  /**
   * 内部定义一个Properties属性变量用于存储传递的参数，先对driverProperties（里面保存的是以driver.为前缀设置的配置信息）进行判断，
   * 如果有值直接将其内部的值全部转移到新的properties中，再判断传递的username与password，
   * 并将其保存到properties中，其实这时，properties中保存的是有关数据源连接的基础信息。
   * 
   * 该方法真实的作用是处理参数，获取数据源的方法有同名的doGetConnection(Properties properties)方法实现
   * @param username
   * @param password
   * @return
   * @throws SQLException
   */
  private Connection doGetConnection(String username, String password) throws SQLException {
    Properties props = new Properties();
    if (driverProperties != null) {
      props.putAll(driverProperties);
    }
    if (username != null) {
      props.setProperty("user", username);
    }
    if (password != null) {
      props.setProperty("password", password);
    }
    return doGetConnection(props);
  }
  
  private Connection doGetConnection(Properties properties) throws SQLException {
	//驱动器初始化
    initializeDriver();
    //通过调用DriverManager的getConnection方法来获取数据库连接connection
    Connection connection = DriverManager.getConnection(url, properties);
    //调用configureConnection()方法进行数据库连接的配置，配置内容：自动提交（boolean值）与事务级别
    configureConnection(connection);
    return connection;
  }
  /**
   * 驱动器初始化的方法，该方法使用synchronized进行修饰，表示这是一个同步方法，同一时刻只能被一处调用，这个方法的作用是加载驱动器类，
   * 	并将其实例注册到DriverManager中，同时将其保存到本实例的registeredDrivers中。
   * @throws SQLException
   */
  private synchronized void initializeDriver() throws SQLException {
    if (!registeredDrivers.containsKey(driver)) {
      Class<?> driverType;
      try {
        if (driverClassLoader != null) {
          driverType = Class.forName(driver, true, driverClassLoader);
        } else {
          driverType = Resources.classForName(driver);
        }
        // DriverManager requires the driver to be loaded via the system ClassLoader.
        // http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
        Driver driverInstance = (Driver)driverType.newInstance();
        //DriverProxy，是一个驱动代理，这个类是以静态代理类的方式定义的，其实现了Driver接口，实现了Driver接口中的所有抽象方法，
        //是一个真正的代理类，代理Driver真正的实现类，即真正起作用的驱动类实例，代理类将驱动类的所有方法全部保护起来
        DriverManager.registerDriver(new DriverProxy(driverInstance));
        registeredDrivers.put(driver, driverInstance);
      } catch (Exception e) {
        throw new SQLException("Error setting driver on UnpooledDataSource. Cause: " + e);
      }
    }
  }
  /**
   * 数据源配置，配置内容：自动提交（boolean值）与事务级别
   * @param conn
   * @throws SQLException
   */
  private void configureConnection(Connection conn) throws SQLException {
    if (autoCommit != null && autoCommit != conn.getAutoCommit()) {
      conn.setAutoCommit(autoCommit);
    }
    if (defaultTransactionIsolationLevel != null) {
      conn.setTransactionIsolation(defaultTransactionIsolationLevel);
    }
  }
  /**
   * 内部代理类，实现对java.sql.Driver的代理
   * @author hsh
   *
   */
  private static class DriverProxy implements Driver {
    private Driver driver;

    DriverProxy(Driver d) {
      this.driver = d;
    }

    @Override
    public boolean acceptsURL(String u) throws SQLException {
      return this.driver.acceptsURL(u);
    }

    @Override
    public Connection connect(String u, Properties p) throws SQLException {
      return this.driver.connect(u, p);
    }

    @Override
    public int getMajorVersion() {
      return this.driver.getMajorVersion();
    }

    @Override
    public int getMinorVersion() {
      return this.driver.getMinorVersion();
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException {
      return this.driver.getPropertyInfo(u, p);
    }

    @Override
    public boolean jdbcCompliant() {
      return this.driver.jdbcCompliant();
    }

    // @Override only valid jdk7+
    @Override
	public Logger getParentLogger() {
      return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }
  }

  @Override
  public <T> T unwrap(Class<T> iface) throws SQLException {
    throw new SQLException(getClass().getName() + " is not a wrapper.");
  }

  @Override
  public boolean isWrapperFor(Class<?> iface) throws SQLException {
    return false;
  }
  /**
   * 获取这个DataSource所使用的所有Logger的父Logger。
   */
  // @Override only valid jdk7+
  @Override
public Logger getParentLogger() {
    // requires JDK version 1.6
    return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
  }

}
